package com.jly.edu.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jly.edu.common.dto.SysMenuDto;
import com.jly.edu.entity.SysMenu;
import com.jly.edu.entity.SysUser;
import com.jly.edu.mapper.SysMenuMapper;
import com.jly.edu.service.SysCommonService;
import com.jly.edu.service.SysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jly.edu.service.SysUserService;
import com.jly.edu.utils.ConverUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 作者：纪联友
 * @since 2021-10-23
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysCommonService sysCommonService;

    /**
     * 获取当前用户菜单导航
     */
    @Override
    public List<SysMenuDto> getCurrentUserNav() {
        String username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SysUser sysUser = sysUserService.getByUsername(username);
        // 获取用户的所有菜单
        List<Long> menuIds = sysCommonService.getNavMenuIds(sysUser.getId());
        if(menuIds != null && menuIds.size() >0){
            List<SysMenu> menus = buildTreeMenu(this.listByIds(menuIds));
            return ConverUtil.convertList(buildTreeMenu(menus),SysMenuDto.class);
        }
        return new ArrayList<>();
    }

    @Override
    public List<SysMenu> getAllMenuList() {

        List<SysMenu> sysMenuList = this.list(new QueryWrapper<SysMenu>().orderByAsc("order_num"));
        if(sysMenuList != null && sysMenuList.size() >0){
            return buildTreeMenu(sysMenuList);
        }
        return new ArrayList<>();
    }
    private List<SysMenu> buildTreeMenu(List<SysMenu> menus) {

        List<SysMenu> finalMenus = new ArrayList<>();

        // 先各自寻找到各自的孩子
        for (SysMenu menu : menus) {

            for (SysMenu e : menus) {
                if (menu.getId() == e.getParentId()) {
                    menu.getChildren().add(e);
                }
            }

            // 提取出父节点
            if (menu.getParentId() == 0L) {
                finalMenus.add(menu);
            }
        }

        System.out.println(JSONUtil.toJsonStr(finalMenus));
        return finalMenus;
    }

}
